<template>
  <!-- hidden PageHeaderWrapper title demo -->
  <page-header-wrapper :title="false" content="pipeline管理">
    <a-card :body-style="{padding: '24px 32px'}" :bordered="false">
      <div class="table-operator">
        <a-button type="primary" style="margin-right: 0px;">项目</a-button>
        <a-select v-model="query.projectId" style="width: 200px">
          <a-select-option v-for="(item, index) in projectList" :key="index" :value="item.id">{{item.projectName}}</a-select-option>
        </a-select>
        <a-button type="primary" icon="plus" style="margin-left: 75%;" @click="createPipeline">创建管道</a-button>
      </div>
      <Collapse v-model="activeGroupKeys">
        <CollapsePancel :key="item.id" :header="item.groupName" v-for="item in groupPipelineList">
          <div style="padding: 0px 32px">
            <a-list class="demo-loadmore-list" item-layout="horizontal" :data-source="item.pipelineList">
              <a-list-item slot="renderItem" slot-scope="pipeline, index">
                <a-dropdown slot="actions">
                  <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                    操作 <a-icon type="down" />
                  </a>
                  <a-menu slot="overlay">
                    <a-menu-item>
                      <a href="javascript:;" @click="toEditPipeline(pipeline.id)">编辑</a>
                    </a-menu-item>
                    <a-menu-item v-if="pipeline.status == 0">
                      <a href="javascript:;" @click="deletePipeline(pipeline.id, pipeline.name)">删除</a>
                    </a-menu-item>
                    <a-menu-item v-if="pipeline.status == 2 || pipeline.status == 3">
                      <a href="javascript:;" >停止</a>
                    </a-menu-item>
                    <a-menu-item v-if="pipeline.status == 2 || pipeline.status == 3">
                      <a href="javascript:;" @click="showLogs(pipeline.id)">查看日志</a>
                    </a-menu-item>
                  </a-menu>
                </a-dropdown>
                <a-list-item-meta
                  :description="pipeline.description"
                >
                  <a slot="title">
                    {{ pipeline.name }}
                    <Tag v-if="pipeline.status != 3" :color="statusColor(pipeline.status)">{{convertStatusName(pipeline.status)}}</Tag>
                    <Tag v-if="pipeline.status == 3" :color="statusColor(pipeline.status)"><a @click="showError(pipeline.log)">{{convertStatusName(pipeline.status)}} <a-icon type="alert" /> </a></Tag>
                    <span style="color: #bcbfc3;font-weight: 300;">上次更新时间：<span v-text="pipeline.modifyTime.replace('T', ' ')"></span></span>
                    <span v-text="pipeline.log" style="color: red;margin-left: 20px"></span>
                  </a>
                </a-list-item-meta>
                <Tag color="magenta">workers: {{pipeline.workers}}</Tag>
                <Tag color="green">host: {{pipeline.expectRunHost ? pipeline.expectRunHost : pipeline.actualRunHost}}</Tag>

              </a-list-item>
            </a-list>
          </div>
        </CollapsePancel>
      </Collapse>
    </a-card>
    <a-drawer title="日志信息" width="1200" :visible="showLogFlag" @close="hideLogs">
      <div id="log_div" style="width: 100%;min-height: 800px;border: 1px solid #ccd1d3;background-color: #f5f5f5"></div>
    </a-drawer>
  </page-header-wrapper>
</template>

<script>
  import { upload, getVersionList } from '@/api/logstash'
  import { getProjectList } from '@/api/logstash_project'
  import { queryGroupPipeline } from '@/api/logstash_group'
  import { deletePipeline } from '@/api/logstash_pipeline'
  import { Collapse, Tag } from 'ant-design-vue'
  import RoleModal from '../other/modules/RoleModal'
  import { getUUID } from '@/utils/util'

  const columns = [
    {
      title: '#',
      scopedSlots: { customRender: 'serial' }
    },
    {
      title: '版本号',
      dataIndex: 'logstash_version'
    },
    {
      title: 'host',
      dataIndex: 'host',
      scopedSlots: { customRender: 'host' }
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: '150px',
      scopedSlots: { customRender: 'action' }
    }
  ]

  export default {
    name: 'LogstashPackage',
    components: {
      Collapse,
      CollapsePancel: Collapse.Panel,
      Tag,
    },
    data () {
      this.columns = columns
      return {
        query:{
          projectId: null
        },
        showList: true,
        dataList: [],
        projectList: [],
        groupPipelineList: [],
        activeGroupKeys: [],
        statusColorMap: {0: "volcano", 1: "lime", 2: "green", 3: "red"},
        statusNameMap: {0: "未运行", 1: "调度中", 2: "运行中", 3: "运行错误"},
        intervalId: null,
        showLogFlag: false,
        socket: null,
        socketPath: "ws://127.0.0.1:8099/llog/",
        logDiv: null
      }
    },
    methods: {
      createPipeline () {
        this.$router.push({ path: '/pipeline/edit' })
      },
      loadData () {
        const me = this
        getVersionList(this.query).then(res => {
          if (res.code === 200) {
            me.dataList = res.data
          }
        })
      },
      getProjectList () {
        getProjectList().then(res => {
          this.projectList = res.data
          if(this.projectList.length > 0){
            this.query.projectId = this.projectList[0].id
          }else{
            this.$warning({
              title: '重要提示',
              content: '请建立项目',
              onOk: function () {
                me.$router.push({ path: '/data-control/project' })
              }
            });
          }
        })
      },
      queryGroupPipeline () {
        queryGroupPipeline({
          projectId: this.$store.state.project.projectId
        }).then(res => {
          if(res.code == 200){
            this.groupPipelineList = res.data
            if(this.groupPipelineList.length > 0){
              this.activeGroupKeys = [this.groupPipelineList[0].id]
            }
          }
        })
      },
      toEditPipeline (id) {
        this.$router.push({ path: '/pipeline/edit', query: {id: id} })
      },
      deletePipeline (id, name) {
        const me = this
        me.$confirm({
          title: '提示',
          content: '请确认是否删除【' + name + '】管道',
          onOk() {
            deletePipeline(id).then(res => {
              if(res.code == 200){
                me.$message.success('删除成功')
                me.queryGroupPipeline()
              }
            })
          },
          onCancel() {},
        });
      },
      statusColor (status) {
        return this.statusColorMap[status]
      },
      convertStatusName (status) {
        return this.statusNameMap[status]
      },
      dataRefreh() {
        // 计时器正在进行中，退出函数
        if (this.intervalId != null) {
          return;
        }
        // 计时器为空，操作
        this.intervalId = setInterval(() => {
          console.log("刷新" + new Date());
          this.queryGroupPipeline();
        }, 10000);
      },
      sendWebsocket() {
        // 计时器正在进行中，退出函数
        if (this.intervalWebsocketId != null) {
          return;
        }
        // 计时器为空，操作
        this.intervalWebsocketId = setInterval(() => {
          this.socket.send("1")
        }, 1000);
      },
      clearWebsocket() {
        clearInterval(this.intervalWebsocketId)
        this.intervalWebsocketId = null
        if(this.socket){
          this.socket.close()
        }
        this.socket = null
        if(this.logDiv){
          this.logDiv.innerHTML = ''
        }
      },
      // 停止定时器
      clear() {
        clearInterval(this.intervalId); //清除计时器
        this.intervalId = null; //设置为null
      },
      showLogs(pipelineId) {
        this.showLogFlag = true
        this.connWebSocket(pipelineId)
      },
      hideLogs() {
        this.showLogFlag = false
        this.clearWebsocket()
      },
      connWebSocket(pipelineId) {
        this.socket = new WebSocket("ws://127.0.0.1:8099/llog/" + pipelineId + "-" + getUUID())
        this.socket.onopen = this.openWebsocket
        this.socket.onerror = function () {
          console.log("连接错误")
        }
        this.socket.onclose = this.clearWebsocket
        this.socket.onmessage = this.showLogContent
      },
      openWebsocket() {
        this.sendWebsocket()
        this.logDiv = document.getElementById("log_div");
        this.logDiv.innerHTML = ''
      },
      showLogContent(msg) {
        let p = document.createElement("p")
        p.appendChild(document.createTextNode(msg.data))
        this.logDiv.appendChild(p)
      },
      showError(error) {
        this.$error({
          title: '运行错误',
          content: error
        });
      }

  },
    created () {
      this.getProjectList()
    },
    mounted () {
      this.loadData()
      this.queryGroupPipeline()
      this.dataRefreh()

    },
    destroyed() {
      this.clear()
      this.clearWebsocket()
    }
  }
</script>
<style>
  .ant-list-item {
    padding: 6px 0px !important;
  }
</style>